#include <iostream>
#include <string>
#include <fstream>
#include <stdio.h>
#include <cstring>

#define filename    "./test.txt"
#define DELIMITER   " "

int16_t thr[6] = {2000,2001,2002,2003,2004,2005};
int16_t num[6];

int main(void)
{
    std::string write_buffer;
    std::string read_buffer;
    std::string Delimiter = DELIMITER;


    for (uint8_t i = 0; i < (sizeof(thr)/sizeof(int16_t)); i++)
    {
        write_buffer += std::to_string(thr[i]);
        write_buffer += Delimiter;
    }
    std::cout << "write_buffer:" << write_buffer << std::endl;
    

    std::fstream fs;
RE_OPEN:
    fs.open(filename, std::ios::in);

    // 判断文件是否存在
    if (! fs.is_open())
    {
        std::cout << "文件不存在，创建该文件，并写入默认值" << std::endl;

        fs.open(filename, std::ios::out);
        if(fs.is_open())
        {
            std::cout << "创建文件成功，写入默认值" << std::endl;
            fs << write_buffer << std::endl;
            fs.close();
        }
        else
        {
            std::cout << "创建文件失败" << std::endl;
            fs.close();
            goto RE_OPEN;
        }
    }

    std::cout << "文件存在，读取文件的阈值，开始下发" << std::endl;
    std::string data((std::istreambuf_iterator<char>(fs)),
                           (std::istreambuf_iterator<char>()));

    // std::cout << "data:" << data << std::endl;
    read_buffer = data;
    std::cout << "read_buffer:" << read_buffer << std::endl;

    fs.close();
    

    for (uint8_t i = 0; i < (sizeof(thr)/sizeof(int16_t)); i++)
    {
        std::string temp = read_buffer.substr(0, read_buffer.find(" "));
        read_buffer = read_buffer.substr(read_buffer.find(Delimiter) + Delimiter.length());
        // std::cout << "temp:" << temp << std::endl;
        num[i] = std::stoi(temp);
        std::cout << "num:" << num[i] << std::endl;
    }


    return 0;
}